package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("sessions")
public class SessionController {
    @Autowired
    public IUserService userService;

    @PostMapping
    public JSONResult login(@RequestParam String email, @RequestParam String password){
        JSONResult jsonResult = new JSONResult();
        try {
            User user = userService.login(email, password);
            //把当前用户返回到移动端,让移动端存储当前用户的信息,当其想要获取当前用户信息,不在需要发送请求
            jsonResult.setObj(user);
            //把当前用户放入session中,用来判断当前登录的用户是否是不需要资源的(拦截器中使用)
            UserContext.setCurrentUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark(e.getMessage());
        }
        return jsonResult;
    }

    @DeleteMapping
    public JSONResult logout(HttpSession session){
        session.invalidate();
        return new JSONResult();
    }

}
